/*
 * vfile_opsFILE.cpp
 *
 *  Created on: Jul 25, 2009
 *      Author: kurt
 */

#include "vfileops/vfileOpsFILE.h"
#include <cstdio>
#include <pspiofilemgr.h>
#include <string.h>
using namespace std;

bool vFILE_open(const char * fname, const char * mode, void *& stream)
{
	if(stream != NULL)
		vFILE_close(stream);
	SceUID * id = new SceUID;
	stream = id;
	*id = -1;
	int flags = 0;
	
	if(strcmp(mode,"r") == 0 || strcmp(mode,"rb") == 0)
		flags = PSP_O_RDONLY;
	else if(strcmp(mode,"w") == 0 || strcmp(mode,"wb") == 0)
		flags = PSP_O_WRONLY | PSP_O_CREAT;
	else if(strcmp(mode,"a") == 0 || strcmp(mode,"ab") == 0)
		flags = PSP_O_APPEND;
	else if(strcmp(mode,"r+") == 0 || strcmp(mode,"rb+") == 0)
		flags = PSP_O_RDWR;
	else if(strcmp(mode,"w+") == 0 || strcmp(mode,"wb+") == 0)
		flags = PSP_O_CREAT | PSP_O_RDWR;
	else if(strcmp(mode,"a+") == 0 || strcmp(mode,"ab+") == 0)
		flags = PSP_O_APPEND | PSP_O_RDWR;
	
	*id = sceIoOpen(fname,flags,0777);
	if(id != NULL && *id > 0)
		return true;
	delete id;
	stream = NULL;
	return false;
}
void vFILE_close(void *& stream)
{
	SceUID * id = (SceUID *)stream;
	if(id != NULL && *id > 0)
		sceIoClose(*id);
	delete id;
	stream = NULL;
}		
int vFILE_flush(void * stream)
{
	return 0;
}
int vFILE_seek(void * stream, long offset, int origin)
{
	SceUID * id = (SceUID *)stream;
	if(id != NULL && *id > 0)
		return sceIoLseek32(*id,offset,origin);
	return 0;
}
bool vFILE_eof(void * stream)
{
	SceUID * id = (SceUID *)stream;
	if(id != NULL && *id > 0)
	{
		long cur = sceIoLseek32(*id,0,SEEK_CUR);
		long end = sceIoLseek32(*id,0,SEEK_END);
		if(cur == end)
			return true;
		sceIoLseek32(*id,cur,SEEK_SET);
		return false;
	}
	return true;;
}
long vFILE_tell(void * stream)
{
	SceUID * id = (SceUID *)stream;
	if(id != NULL && *id > 0)
		return sceIoLseek32(*id, 0, SEEK_CUR);
	return 0;
}
int vFILE_read(void * buffer, size_t size, size_t num, void * stream)
{
	SceUID * id = (SceUID *)stream;
	if(id != NULL && *id > 0)
		return sceIoRead(*id,buffer,size * num);
	return 0;
}
int vFILE_write(const void *buffer, size_t size, size_t count, void *stream)
{
	SceUID * id = (SceUID *)stream;
	if(id != NULL && *id > 0)
		return sceIoWrite(*id,buffer,size * count);
	return 0;
}
bool vFILE_error(void * stream)
{
	return false;
}
bool vFILE_is_open(void * stream)
{
	SceUID * id = (SceUID *)stream;
	if(id != NULL && *id > 0)
		return true;
	return false;
}
